<template>
  <el-dialog
    v-model="visible"
    title="溯源码二维码"
    width="500px"
    :before-close="handleClose"
    draggable
    center
  >
    <div class="qrcode-container">
      <!-- 批次信息展示 -->
      <div class="batch-info">
        <h3 class="batch-title">批次信息</h3>
        <div class="info-item">
          <span class="label">生产批次：</span>
          <span class="value">{{ batchData?.batch || '无数据' }}</span>
        </div>
        <div class="info-item">
          <span class="label">商品名称：</span>
          <span class="value">{{ batchData?.storeName || '无数据' }}</span>
        </div>
        <div class="info-item">
          <span class="label">生产企业：</span>
          <span class="value">{{ batchData?.company || '无数据' }}</span>
        </div>
      </div>

      <!-- 二维码展示区域 -->
      <div class="qrcode-section">
        <div class="qrcode-wrapper">
          <canvas ref="qrcodeCanvas" class="qrcode-canvas"></canvas>
        </div>
        <div class="qrcode-tips">
          <p class="tip-text">扫码查看产品溯源信息</p>
          <!-- <p class="tip-desc">支持微信直接扫码查看，无需网络连接</p> -->
        </div>
      </div>

      <!-- 二维码内容预览 -->
      <div class="json-preview">
        <h4 class="preview-title">扫码查看内容：</h4>
        <div class="json-content" v-if="!isEmptyData">
          <pre>{{ qrCodeUrl }}</pre>
        </div>
        <div class="empty-data-tip" v-else>
          <el-icon class="empty-icon"><Warning /></el-icon>
          <span class="empty-text">请完善信息</span>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="downloadQRCode">
          <el-icon><Download /></el-icon>
          下载二维码
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, computed } from 'vue'
import QRCode from 'qrcode'
import { Download, Warning } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 定义接口
interface BatchData {
  id: number
  sid: string
  storeName: string
  batch: string
  expiration: number
  license: string
  company: string
  picture: string
  completeness: number
  creator: string
  creatorDate: string
  updator: string
  updatorDate: string
}

interface TraceabilityData {
  code: number
  message: string
  data: {
    basic: {
      id: number
      sid: number
      batch: string
      expiration: number
      license: string
      company: string
    }
    cultivation: {
      variety: string
      source: string
      rearingDays: number
      brand: string
      rearingLeader: string
      outDate: string
      batch: string
    }
    deepProcessing: {
      team: string
      leader: string
      batch: string
    }
    slaughter: {
      batch: string
      weight: number
    }
  }
}

// Props
const props = defineProps<{
  modelValue: boolean
  batchData: BatchData | null
  traceabilityData: TraceabilityData | null
}>()

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
}>()

// 响应式数据
const visible = ref(false)
const qrcodeCanvas = ref<HTMLCanvasElement>()
const jsonData = ref<string>('')
const qrCodeUrl = ref<string>('')

// 监听弹框显示状态
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal && props.traceabilityData) {
    nextTick(() => {
      generateQRCode()
    })
  }
})

// 监听visible变化，同步到父组件
watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

// 格式化JSON数据用于显示
const formattedJsonData = computed(() => {
  if (!props.traceabilityData) return ''
  return JSON.stringify(props.traceabilityData, null, 2)
})

// 检查data是否为空
const isEmptyData = computed(() => {
  if (!props.traceabilityData || !props.traceabilityData.data) return true
  return Array.isArray(props.traceabilityData.data) && props.traceabilityData.data.length == 0
})

// 生成二维码
const generateQRCode = async () => {
  if (!props.traceabilityData || !qrcodeCanvas.value) return

  try {
    // 将溯源数据转换为JSON字符串
    jsonData.value = JSON.stringify(props.traceabilityData)
    
    // 调试：打印原始数据
    console.log('原始溯源数据:', props.traceabilityData)
    
    // 检查数据是否为空
    if (!props.traceabilityData.data || !Array.isArray(props.traceabilityData.data) || props.traceabilityData.data.length === 0) {
      ElMessage.warning('溯源数据为空，请先完善该批次的溯源信息')
      return
    }
    
    // 获取第一个数据元素
    const traceData = props.traceabilityData.data[0] || {}
    
    // 检查是否有基本信息
    const hasBasicData = traceData?.basic?.company || 
                        traceData?.basic?.license || 
                        props.batchData?.company
    
    if (!hasBasicData) {
      ElMessage.warning('缺少基本信息，无法生成二维码')
      return
    }
    
    // 构建简化的微信友好文本格式（减少内容长度以提高扫描成功率）
    let qrText = `产品溯源信息

基本信息：
批次：${traceData.basic?.batch || props.batchData?.batch || '无'}
企业：${traceData.basic?.company || props.batchData?.company || '无'}
许可证：${traceData.basic?.license || '无'}

养殖信息：
品种：${traceData.cultivation?.variety || '无'}
来源：${traceData.cultivation?.source || '无'}
养殖天数：${traceData.cultivation?.rearingDays || 0}天
负责人：${traceData.cultivation?.rearingLeader || '无'}

加工信息：
团队：${traceData.deepProcessing?.team || '无'}
负责人：${traceData.deepProcessing?.leader || '无'}

屠宰信息：
批次：${traceData.slaughter?.batch || '无'}
重量：${traceData.slaughter?.weight || 0}kg

生成时间：${new Date().toLocaleDateString('zh-CN')}
认证：全程溯源认证`

    // 如果文本过长，使用更简化的版本
    if (qrText.length > 200) {
      qrText = `产品溯源信息

批次：${traceData.basic?.batch || props.batchData?.batch || '无'}
企业：${traceData.basic?.company || props.batchData?.company || '无'}
品种：${traceData.cultivation?.variety || '无'}
负责人：${traceData.cultivation?.rearingLeader || '无'}
重量：${traceData.slaughter?.weight || 0}kg

生成时间：${new Date().toLocaleDateString('zh-CN')}
认证：全程溯源认证`
    }

    // 调试：打印构建的数据
    console.log('构建的二维码文本:', qrText)
    console.log('文本长度:', qrText.length, '字符')
    
    // 生成二维码内容
    const qrContent = qrText
    qrCodeUrl.value = qrText
    
    // 生成二维码
    await QRCode.toCanvas(qrcodeCanvas.value, qrContent, {
      width: 400, // 增大二维码尺寸以提高扫描成功率
      margin: 2, // 减少边距以增加二维码密度
      color: {
        dark: '#000000', // 纯黑色，确保扫描识别
        light: '#ffffff'  // 纯白色背景
      },
      errorCorrectionLevel: 'M' // 使用中等纠错级别，平衡容量和扫描成功率
    })
  } catch (error) {
    console.error('生成二维码失败:', error)
    ElMessage.error('生成二维码失败')
  }
}


// 下载二维码
const downloadQRCode = () => {
  if (!qrcodeCanvas.value) return

  try {
    // 创建下载链接
    const link = document.createElement('a')
    link.download = `溯源码_${props.batchData?.batch || 'unknown'}.png`
    link.href = qrcodeCanvas.value.toDataURL('image/png')
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('二维码下载成功')
  } catch (error) {
    console.error('下载二维码失败:', error)
    ElMessage.error('下载二维码失败')
  }
}

// 关闭弹框
const handleClose = () => {
  visible.value = false
}
</script>

<style scoped>
.qrcode-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 10px 0;
}

.batch-info {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e9ecef;
}

.batch-title {
  margin: 0 0 12px 0;
  color: #2d5a27;
  font-size: 16px;
  font-weight: 600;
}

.info-item {
  display: flex;
  margin-bottom: 8px;
  align-items: center;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
}

.value {
  color: #2d5a27;
  font-weight: 500;
}

.qrcode-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.qrcode-wrapper {
  background: #ffffff;
  border: 2px solid #e9ecef;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: center;
  align-items: center;
}

.qrcode-canvas {
  display: block;
  border-radius: 8px;
}

.qrcode-tips {
  text-align: center;
}

.tip-text {
  margin: 0 0 4px 0;
  color: #2d5a27;
  font-weight: 600;
  font-size: 14px;
}

.tip-desc {
  margin: 0;
  color: #666;
  font-size: 12px;
}

.json-preview {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e9ecef;
}

.preview-title {
  margin: 0 0 12px 0;
  color: #2d5a27;
  font-size: 14px;
  font-weight: 600;
}

.json-content {
  background: #ffffff;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 12px;
  max-height: 200px;
  overflow-y: auto;
}

.json-content pre {
  margin: 0;
  font-size: 12px;
  color: #333;
  line-height: 1.4;
  white-space: pre-wrap;
  word-break: break-all;
}

.empty-data-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 20px;
  background: #fff3cd;
  border: 1px solid #ffc107;
  border-radius: 6px;
  color: #856404;
}

.empty-icon {
  font-size: 16px;
}

.empty-text {
  font-size: 14px;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 0 0 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .qrcode-container {
    gap: 16px;
  }
  
  .batch-info {
    padding: 12px;
  }
  
  .qrcode-wrapper {
    padding: 16px;
  }
  
  .json-content {
    max-height: 150px;
  }
}
</style>
